class_name CardRewards
extends ColorRect

signal card_reward_selected(card: Card)

@export var rewards: Array[Card] = []: set = _set_rewards
@onready var cards: HBoxContainer = %Cards
@onready var skip_button: Button = %SkipButton
@onready var take_button: Button = %TakeButton
@onready var card_tooltip_popup: CardTooltipPopup = %CardTooltipPopup

var selected_card: Card

func _ready() -> void:
	_clear_rewards()
	
	take_button.pressed.connect(func():
		card_reward_selected.emit(selected_card)
		queue_free()
	)
	
	skip_button.pressed.connect(func():
		card_reward_selected.emit(null)
		queue_free()
	)
	
func _input(event: InputEvent) -> void:
	if event.is_action_pressed("ui_cancel"):
		card_tooltip_popup.hide_tooltip()
		
func _clear_rewards() -> void:
	for child in cards.get_children():
		child.queue_free()
	card_tooltip_popup.hide_tooltip()
	selected_card = null
	
func _show_tooltip(card: Card) -> void:
	selected_card = card
	card_tooltip_popup.show_tooltip(card)
	
func _set_rewards(value: Array[Card]) -> void:
	rewards = value
	if not is_node_ready():
		await ready
	_clear_rewards()
	for card in rewards:
		var new_card : CardMenuUI = AutoLoader.CARD_MENU_UI_SCENE.instantiate()
		cards.add_child(new_card)
		new_card.card = card
		new_card.tooltip_requested.connect(_show_tooltip)
